<?php
/*
 * @Author: KingMin 
 * @Date: 2021-07-13 22:34:59 
 * @Last Modified by:   KingMin 
 * @Last Modified time: 2021-07-13 22:34:59 
 * @The authors website: https://www.kingmin.cn  
 */
/**
 * 聊天model
 * @copyright (c) KINGMIN All Rights Reserved
 */
 //加载GatewayClient
// require_once '../lib/gateway.php';

/**
 * gatewayClient 3.0.0及以上版本加了命名空间
 * 而3.0.0以下版本不需要use GatewayClient\Gateway;
 **/
 use GatewayClient\Gateway;
 Gateway::$registerAddress = '127.0.0.1:1238';
class Chat_Model{
    public static function bindUid($client_id, $uid){
        
    }
    // 获取聊天详情
    public static function getChatDetails($id=""){
        if(!$id){
            return false;
        }
        $db = Database::getInstance();
        $wSql="  AND `id`='".$id."' ";
        $sql = "SELECT * FROM `" . DB_PREFIX . "sys_chat_details` WHERE  `isdel`='0' $wSql ;";
        $logs = $db->query($sql);
        
        $data = array();
        foreach ($logs as $key => $v) {
            $v['user']=User_Model::getMemberDetail($v['create_by']);
            $v['payload']=emoji_decode($v['payload']);
            $v['payload']=json_decode($v['payload'],true);
            $v['alldel']=json_decode($v['alldel'],true);
            $v['read']=isBoolStr($v['read']);
            $v['recalled']=isBoolStr($v['recalled']);
            $v['timestamp']=intval($v['timestamp']);
            $data=$v;
        }
        
        return $data;
    }
    // 修改聊天详情
    // // 获取聊天未读条数
    public static function chatReadCount($uid="",$senderId=""){
        if(!$uid){
            return 0;
        }
        $chatSql="";
        if($senderId){
            $chatSql=" AND `senderId`= '$senderId'";
        }
        $db = Database::getInstance();
        
        $totalSql = "SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "sys_chat_details` WHERE  `isdel`='0' AND `recalled`='0' AND `read`='0' AND `receiverId`='".$uid."' $chatSql ;";
        $res = $db->fetch_array($db->query($totalSql));
        
        return intval($res['total']);
    }
    // 获取聊天列表
    public static function getChatList($dt=[], $uid=""){
        $db = Database::getInstance();
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        if(!$uid){
            $output['msg']="参数为空#uid";
            return $output;
        }
        
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
	    $mySql=" AND ( `receiverId`='$uid' OR `senderId`='$uid' ) AND `receiverdel`!='$uid' AND `senderdel`!='$uid' ";
	    
        if(@$dt['chattype']){
            $wSql=" AND `chattype` = ".$dt['chattype']." " ;
        }else{
            $output['msg']="参数为空#chattype";
            return $output;
        }
        
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "sys_chat` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "sys_chat`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        // return $sql;
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        
        foreach ($logs as $key => $v) {
            $chatuser=$v['receiverId'];
            $v['isdeltype']="senderdel";
            if($v['receiverId']==$uid){
                $chatuser=$v['senderId'];
                $v['isdeltype']="receiverdel";
            }
            $v['chatuser']=User_Model::getMemberDetail($chatuser);
            $v['user']=User_Model::getMemberDetail($v['create_by']);
            $v['first']=self::getChatDetails($v['first']);
            $v['last']=self::getChatDetails($v['last']);
            $v['read']=self::chatReadCount($uid,$chatuser);
            $v['path']='/views/chat/index?id='.$chatuser;
            $v['subtext']="";
            if($v['last']){
                if($v['last']['type']=='text'){
                    $v['subtext']=$v['last']['payload']['text'];
                }
                if($v['last']['type']=='image'){
                    $v['subtext']='[图片]';
                }
                if($v['last']['type']=='video'){
                    $v['subtext']='[视频]';
                }
                if($v['last']['type']=='audio'){
                    $v['subtext']='[语音]';
                }
            }
            if($v['last']['recalled']=='1'){
                $v['subtext']='[消息已撤回]';
            }
            if(@$v['last']['alldel']){
                if(in_array($uid,$v['last']['alldel'])){
                    $v['subtext']='[消息已删除]';
                }
            }
            $v['time']=smartDate(strtotime($v['update_time']),true);
            $v['onLine']=isUserOnLine($chatuser,true);
            $data[]=$v;
        }
        
        $output['list']=$data;
        return $output;
        
    }
    // 是否删除了聊天信息
    public static function isChatAllDel($uid){
        if(!$uid){
            return "";
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "sys_chat_details`  WHERE  `isdel`='0' AND `alldel` LIKE '%$uid%';";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data ="";
        foreach ($logs as $key => $v) {
            $data.=" AND `id`!='".$v['id']."' ";
        }
        return $data;
    }
    // 获取聊天记录
    public static function getChatDetailsList($dt=[], $uid=""){
        $db = Database::getInstance();
        @$isAll=$dt['pages']['isAll'];
        
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
			'$dt'=>$dt
	    ];
        $wSql="";$mySql='';$isfym="";$delSql=self::isChatAllDel($uid);
        $bySql="ORDER BY id DESC ";
        if(@$dt['receiverId']){
            $receiverId=$dt['receiverId'];
            unset($dt['receiverId']);
        }else{
            $output['msg']="参数为空";
            return $output;
        }
        if(@$dt['senderId']){
            $senderId=$dt['senderId'];
            unset($dt['senderId']);
        }else{
            $output['msg']="参数为空";
            return $output;
        }
	    $mySql=" AND ( `receiverId`='$receiverId' OR `senderId`='$receiverId' )  AND ( `receiverId`='$senderId' OR `senderId`='$senderId' )  ";
	    
        if(@$dt['chattype']){
            $wSql=" AND `chattype` = ".$dt['chattype']." " ;
        }else{
            $output['msg']="参数为空";
            return $output;
        }
        
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "sys_chat_details` WHERE  `isdel`='0'   $wSql $mySql $delSql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "sys_chat_details`  WHERE  `isdel`='0'  $wSql $mySql $delSql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        foreach ($logs as $key => $v) {
        //   $v['user']=User_Model::getMemberDetail($v['create_by']);
            $v['payload']=emoji_decode($v['payload']);
            $v['payload']=json_decode($v['payload'],true);
            $v['alldel']=json_decode($v['alldel'],true);
            $v['read']=isBoolStr($v['read']);
            $v['recalled']=isBoolStr($v['recalled']);
            $v['timestamp']=intval($v['timestamp']);
            $data[]=$v;
        }
        if(@$dt['list']){
            $output['list']=$data;
        }else{  
            $output['list']=array_reverse($data);
        }
        $output['delsql']=$delSql;
        return $output;
    }
    // 发送消息
    public static function sendMessage($dt=[],$uid=""){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        @$uid=$dt['senderId'];
        if(!$uid){
            ajaxReturn(401,"用户UID为空",$uid);
        }
        $dt['create_by']=$uid;
        $dt['update_by']=$uid;
        
        if(@$dt['payload']){
            if(!is_string($dt['payload'])){
                $dt['payload']=json_encode($dt['payload'],JSON_UNESCAPED_UNICODE);
            }
           $dt['payload']=emoji_encode($dt['payload']);
        }
        
        $db = Database::getInstance();
        $sql=addSqlConvert("sys_chat_details",$dt);
        
        $baby=$db->query($sql);
        $id=$db->insert_id();
        $dt['first']=$id;
        $dt['last']=$id;
        self::addchatlist($dt);
        $chatData=$dt;
        $chatData['id']=$id.'';
        $chatData['payload']=json_decode($chatData['payload'],true);
        $message=gatewayReturn (200,"chat", '发来一条新消息',$chatData);
        self::sendToUid($dt['receiverId'],$message);
        // self::sendToUid($dt['senderId'],$message);
        // ajaxReturn(200,"新增消息成功",$dt);
        // return $dt;
        return $id.'';
    }
         // 添加会话列表
    public static function addchatlist($dt){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        if(@$dt['receiverId']){
            $receiverId=$dt['receiverId'];
            unset($dt['receiverId']);
        }else{
            ajaxReturn(404,'参数为空');
        }
        if(@$dt['senderId']){
            $senderId=$dt['senderId'];
            unset($dt['senderId']);
        }else{
            ajaxReturn(404,'参数为空');
        }
        $db = Database::getInstance();
        
        $mySql=" AND ( `receiverId`='$receiverId' OR `senderId`='$receiverId' )  AND ( `receiverId`='$senderId' OR `senderId`='$senderId' )  ";
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "sys_chat` WHERE 1 $mySql ;";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['id']){
            $db->query('UPDATE `'.DB_PREFIX."sys_chat` SET `isdel`='0',`views`=views+1,`receiverdel`='0',`senderdel`='0',`last`='".$dt['last']."'  WHERE `id`='".$list['id']."' ");
            // ajaxReturn(200,"修改消息列表成功",$list);
            return true;
        }else{
            $addt=[
                "create_by"=>$senderId,
                "update_by"=>$senderId,
                "receiverId"=>$receiverId,
                "senderId"=>$senderId,
                "first"=>$dt['first'],
                "last"=>$dt['last'],
                "chattype"=>$dt['chattype'],
                "views"=>1
                ];
            $sql=addSqlConvert("sys_chat",$addt);

            // ajaxReturn(400,"参数为空",$sql);
            // return $sql;
            $add=$db->query($sql);
            // $id=$db->insert_id();
            // ajaxReturn(200,"新增消息列表成功",$addt);
            
            return true;
        }
    }
    
    // 修改聊天记录(标记已读)
    public static function chatMarkRead($receiverId,$senderId){
        if(@!$receiverId){
            return false;
        }
        if(@!$senderId){
            return false;
        }
        @$uid=$senderId;
        
        $wSql=" `isdel`='0' AND `receiverId`='$senderId' AND `senderId`='$receiverId' AND `read`='0'";
        $db = Database::getInstance();
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "sys_chat_details`  WHERE   $wSql ;";
        $logs = $db->query($sql);
        $chatData = array();
        foreach ($logs as $key => $v) {
            $v['payload']=emoji_decode($v['payload']);
            $v['payload']=json_decode($v['payload'],true);
            $v['alldel']=json_decode($v['alldel'],true);
            $v['read']=isBoolStr($v['read']);
            $v['recalled']=isBoolStr($v['recalled']);
            $v['timestamp']=intval($v['timestamp']);
            $chatData[]=$v;
        }
        
        if(count($chatData)>0){
            $dt["read"]=1;
            
            $sql=upSqlConvert('sys_chat_details',$dt,$wSql);
            //   return $sql;
            $query = $db->query($sql);
            
            if($query){
                $message=gatewayReturn (200,"readChat", '标记已读',$chatData);
                self::sendToUid($receiverId,$message);
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
        
    }
    // 撤回消息
    public static function chatRecalled($id){
        if(!$id){
            return false;
        }
        $chat=self::getChatDetails($id);
    }
    public static function sendToUid($uid,$message){
        // gatewayReturn ($state="300",$type="", $msg = '操作成功', $data = array()
        // chatReturn ($state="300", $msg = '操作成功', $data = array())
       Gateway::sendToUid($uid,$message);
    }
    
}